<?php

namespace Yj\Generator\Core\Processor;

use Hyperf\Database\ConnectionResolverInterface;
use Hyperf\Database\Schema\Builder as SchemaBuilder;
use Hyperf\DbConnection\Db;
use Yj\Generator\Core\Config;
use Yj\Generator\Core\Model\EloquentModel;
use Yj\Generator\Core\Model\NamespaceModel;
use Yj\Generator\Core\Model\PropertyModel;
use Yj\Generator\Core\Model\VirtualPropertyModel;

/**
 * @Notes: []
 * @User: zwc
 * @Date: 2022/3/1 17:02
 */
class FieldProcessor
{
    /**
     * @inheritdoc
     */
    public function process(EloquentModel $model, Config $config)
    {
        /** @var SchemaBuilder $builder */
        $builder = Db::connection('default');
//        $builder = App(ConnectionResolverInterface::class)->connection('default');
        $prefix = $builder->getConnection()->getTablePrefix();
        $schemaManager = $builder->getConnection()->getDoctrineSchemaManager();

        $tableDetails = $schemaManager->listTableDetails($prefix . $model->getTableName());
        $primaryColumnNames = $tableDetails->getPrimaryKey() ? $tableDetails->getPrimaryKey()->getColumns() : [];
        $columnNames = [];
        foreach ($tableDetails->getColumns() as $column) {
            $model->addProperty(new VirtualPropertyModel(
                $column->getName(),
                $column->getType()->getName()
            ));
            if (!in_array($column->getName(), $primaryColumnNames)) {
                $columnNames[] = $column->getName();
            }
        }
        $fillableProperty = new PropertyModel('fillable');
        $fillableProperty->setAccess('protected')->setValue($columnNames);
        $model->addProperty($fillableProperty);
        return $this;
    }


}